//
//  RootViewController.m
//  斗鸡TV
//
//  Created by admin on 16/3/10.
//  Copyright © 2016年 admin. All rights reserved.
//

#import "RootViewController.h"
#import "ApplicitonClass.h"


@interface RootViewController ()
{
    
}


@end

@implementation RootViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [UIColor colorWithRed:236 / 255.0 green:236 / 255.0 blue:236 / 255.0 alpha: 1.0];
    
    [ApplicitonClass getInstance].isflag = NO;
    
    
}


/**
 原生网络请求

 @param url url
 @param dic 参数
 */
-(void)http_get_request:(NSString *)url parameters:(NSDictionary *)dic successBlock:(void (^)(NSDictionary*))success errorBlock:(void (^)(NSError *))failerror{
    
    NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.timeoutIntervalForRequest = 10;
    NSURLSession * session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
    
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"GET";
    [request setValue:@"application/json" forHTTPHeaderField:@"content-Type"];
    [request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Accept"];
    
    if (dic) {
        
        NSData * jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        request.HTTPBody = jsonData;
    }
    
    NSURLSessionDataTask * dataTask = [session dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       
        if (error == nil) {
            
            
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            success(dic);
        }else{
            
            failerror(error);
            
        }
        
    }];
//    NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//
//        if (error == nil) {
//
//
//            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//            success(dic);
//        }else{
//
//            failerror(error);
//
//        }
//      
//    }];
    
    //发起请求
    [dataTask resume];
    
}


-(void)httpGetUrl:(NSString *)urlStr params:(NSDictionary *)params successBlock:(void (^)(NSDictionary*))success errorBlock:(void (^)(NSError *))failerror
{
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes =
    [NSSet setWithObjects:@"application/json", @"text/json", @"text/plain",
     @"text/html", nil];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:urlStr parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
        NSLog(@"%@",downloadProgress.localizedDescription);
        //数据请求的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功
        NSDictionary * dict = (NSDictionary *)responseObject;
        
        success(dict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //失败
         failerror(error);
    }];

}

-(void)httpPostUrl:(NSString *)urlStr params:(NSDictionary *)params successBlock:(void (^)(NSDictionary*))success errorBlock:(void (^)(NSError *))failerror
{
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes =
    [NSSet setWithObjects:@"application/json", @"text/json", @"text/plain",
     @"text/html", nil];
    [manager POST:urlStr parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
         NSLog(@"%@",uploadProgress.localizedDescription);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * dict = (NSDictionary *)responseObject;
        
        success(dict);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failerror(error);
        
    }];
    
}

-(void)popBackViewController
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)showError:(NSString *)title
{
    [SVProgressHUD showErrorWithStatus:title];
    [self dispatchMainAfter:1.4
                      block:^{
                          [SVProgressHUD dismiss];
                      }];
}

- (void)showMessage:(NSString *)title
{
    [SVProgressHUD showWithStatus:title];
    [self dispatchMainAfter:1.4
                      block:^{
                          [SVProgressHUD dismiss];
                      }];
}

- (void)showSuccess:(NSString *)title
{
    [SVProgressHUD showSuccessWithStatus:title];
    [self dispatchMainAfter:1.4
                      block:^{
                          [SVProgressHUD dismiss];
                      }];
}

- (void)showLoading
{
    
    [SVProgressHUD showWithStatus:@"加载中..."
                         maskType:SVProgressHUDMaskTypeNone];
}

-(void)dismissLoading
{
     [SVProgressHUD dismiss];
}
#pragma mark - HUD Handler
- (void)dispatchMainAfter:(NSTimeInterval)delay block:(void (^)())block {
    dispatch_after(
                   dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)),
                   dispatch_get_main_queue(), ^{
                       block();
                   });
    

}

//消息提示框 传递block参数
- (void)showAlert:(NSString *)title CancelBlock:(void (^)())cancleBlock OkBlock:(void (^)())okBlock
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"" message:title preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        cancleBlock();
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        okBlock();
        
    }]];
    
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}




-(void)dealloc
{
    NSLog(@"========%@ is dealloc",self);
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
